extends Node
class_name SlimeState
## 用来控制敌人状态和移动
@export var slime: Slime
@onready var sprite: AnimatedSprite2D = %sprite
@onready var state_chart: StateChart = %StateChart
@onready var walk: AtomicState = %walk
@onready var die: AtomicState = %die
@onready var attack: AtomicState = %attack
@onready var run_away: AtomicState = %runAway
@onready var hurt: AtomicState = %hurt
@onready var slime_animations: SlimeAnimations = %SlimeAnimations
@onready var enemy_hit_box_component: EnemyHitBoxComponent = %EnemyHitBoxComponent
@onready var enemy_health_component: EnemyHealthComponent = %EnemyHealthComponent
@onready var attack_area: Area2D = %AttackArea
@onready var slime_skill: SlimeSkill = %SlimeSkill
@onready var animation_player: AnimationPlayer = %AnimationPlayer

## 攻击事件间隔计时
var attack_timer: float = 0
## 狂暴事件计时
var rage_enter_timer: float = 0 
## 攻击目标
var enemy = []

func _ready() -> void:
	# 连接所有状态信号
	walk.state_physics_processing.connect(on_walk_physics_processing)
	die.state_entered.connect(on_die_entered)
	attack.state_physics_processing.connect(on_attack_physics_processing)
	hurt.state_entered.connect(on_hurt_entered)
	slime.die.connect(on_die)
	enemy_health_component.hurt.connect(on_hurt)
	attack_area.area_entered.connect(_on_attack_area_area_entered)
	attack_area.area_exited.connect(_on_attack_area_area_exited)
	
func state_send_event(_name: String):
	state_chart.send_event(_name)
	
#region 状态处理逻辑
## 行走状态物理处理
func on_walk_physics_processing(_delta):
	if animation_player.is_playing():
		return
	# 检查玩家是否隐身
	var player_is_stealthed = false
	player_is_stealthed = EnemyManager.is_player_stealthed()
	
	if not player_is_stealthed:
		rage_enter_timer += _delta
		slime_animations.anim_play("walk")
		slime.velocity = slime.get_safe_velocity()
		slime.move_and_slide()
		if !enemy.is_empty():
			state_send_event("to_attack")
	else:
		slime_animations.anim_play("idle")
		slime.velocity = Vector2.ZERO
		# 不执行move_and_slide()，也不增加rage_enter_timer

## 死亡状态进入
func on_die_entered():
	state_send_event("to_die")
	set_physics_process(false)
	sprite.play("die")
	await sprite.animation_finished
	var tween = create_tween()
	tween.tween_property(owner,"modulate",Color(1,1,1,0),2)
	await tween.finished
	# 计算剩余的分裂史莱姆数量（减去自己）
	var remaining_after_self = get_tree().get_nodes_in_group("boss_slime").size() - 1
	var should_emit_boss_die = remaining_after_self <= 0
	slime.queue_free()
	if should_emit_boss_die:
		EventBus.push_event("boss_die")

## 受伤状态进入
func on_hurt_entered():
	if animation_player.current_animation.begins_with("attack"):
		state_send_event("to_attack")
		return

	animation_player.play("hurt")
	await animation_player.animation_finished
	
	if enemy:
		state_send_event("to_attack")
	else:
		# 返回行走状态
		state_send_event("to_walk")

#endregion


func _on_attack_area_area_entered(_area: Area2D) -> void:
	enemy.append(_area)
	state_send_event("to_attack")

func _on_attack_area_area_exited(_area: Area2D) -> void:
	enemy.erase(_area)
	state_send_event("to_walk")

func on_attack_physics_processing(_delta: float):
	# 检查玩家是否隐身
	var player_is_stealthed = EnemyManager.is_player_stealthed()
	
	# 如果玩家隐身，停止攻击并返回行走状态
	if player_is_stealthed:
		state_send_event("to_walk")
		attack_timer = 0
		return
	
	attack_timer += _delta
	# 如果正在攻击，并且动画在播放就直接返回
	if animation_player.current_animation.begins_with("attack") || sprite.is_playing():
		attack_timer = 0
		return
	if attack_timer > slime.slime_stats.get_float("attack_delay"):
		slime.get_safe_velocity()
		attack_timer = 0
		
		# 使用新的冲刺砍击系统
		var _is_dash_attack = slime_skill.dash_attack()
		

func on_die() -> void:
	state_send_event("to_die")

func on_hurt() -> void:
	state_send_event("to_hurt")
